<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <!-- <el-form-item label="角色id" prop="userId">
      <el-input v-model="ruleForm.userId" />
    </el-form-item> -->
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="角色权限" prop="permission">
      <el-tree
        :data="MainRoutes"
        :props="defaultProps"
        show-checkbox
        node-key="path"
        @check="handleCheck"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> 新增 </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { MainRoutes } from '@/router'
import { postRoleListApi } from '@/api/role'

interface RuleForm {
  // userId: string,
  name: string
  permission: []
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  // userId: "",
  permission: []
})

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请填写角色名称', trigger: 'blur' }
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  permission: [
    {
      required: true,
      message: '请勾选角色权限',
      trigger: 'change'
    }
  ]
})
const handleCheck = (_, { checkedKeys }) => {
  console.log(checkedKeys)
  ruleForm.permission = checkedKeys
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!', ruleForm)
      postRoleListApi(ruleForm)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const defaultProps = {
  children: 'children',
  label: (item) => item.meta.title,
  disabled: 'disabled'
}
</script>
